package com.juntuo.platformUtils;


import com.juntuo.Enums.Constants;
import com.juntuo.util.HttpsUtil;
import com.juntuo.util.JsonUtil;
import com.juntuo.util.StreamClosedHttpResponse;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Register Directly Connected Device :
 * This interface is used by NAs to register devices on the IoT platform.
 * After the registration is successful,
 * the IoT platform allocates a device ID for the device,which is used as the unique identifier of the device.
 * Unregistered devices are not allowed to access the IoT platform.
 * In NB-IoT scenarios, the Set device info interface needs to be invoked to set device information after the registration is successful.
 */
public class RegisterDirectlyConnectedDeviceUtil {

	public static void register(String vCode) throws Exception {

        // Two-Way Authentication
        HttpsUtil httpsUtil = new HttpsUtil();
        httpsUtil.initSSLConfigForTwoWay();

        // Authentication，get token
        String accessToken = AuthenticationUtil.login(httpsUtil);

        //Please make sure that the following parameter values have been modified in the Constant file.
		String appId = Constants.APP_ID;
		String urlReg = Constants.BASE_URL+ Constants.DEVICE_REGISTER_URL;

        //please replace the verifyCode and nodeId and timeout, when you use the demo.
        String verifyCode = vCode;
		String nodeId = verifyCode;
        Integer timeout = 0;

        Map<String, Object> paramReg = new HashMap<>();
        paramReg.put("verifyCode", verifyCode.toUpperCase());
        paramReg.put("nodeId", nodeId.toUpperCase());
        paramReg.put("timeout", timeout);

        String jsonRequest = JsonUtil.jsonObj2Sting(paramReg);
        System.out.print("jsonRequest:"+new Date()+" " +jsonRequest);
        Map<String, String> header = new HashMap<>();
        header.put(Constants.HEADER_APP_KEY, appId);
        header.put(Constants.HEADER_APP_AUTH, "Bearer" + " " + accessToken);

        StreamClosedHttpResponse responseReg = httpsUtil.doPostJsonGetStatusLine(urlReg, header, jsonRequest);

        System.out.println("RegisterDirectlyConnectedDevice, response content:");
        System.out.print(responseReg.getStatusLine());
        System.out.println(responseReg.getContent());
        System.out.println();
    }


}
